var mongoose = require('mongoose');
const DataModel = require('../Models/user.model');

//创建
exports.create = function (req, res, next) {
	const dataModel = new DataModel(req.body);
	dataModel.save()
		.then(data => {
			res.json(data);
		})
}
//获取
exports.get = function (req, res, next) {
	var id = req.params.id;

	DataModel.findById(id, function (err, data) {
		res.json(data);
	})
}
//登录判断
exports.checkLogin = function (req, res, next) {
	var name = req.body.name;

	var password=req.body.password;

	var data = {name: name,password: password};
	DataModel.find(data,function(err,data){
		if(data.length>0){
			res.json(data)
		}else{
			res.json({"status":404,"msg":'用户名或密码错误'})
		}
	})
}
//更新操作
exports.update = function (req, res, next) {
	const id = req.params.id;

	DataModel.findByIdAndUpdate(id, { $set: req.body }, { new: false })//找到就更新，没找到就新增
		.then(data => {
			res.json(data);//返回修改前的数据
		})

}
//删除
exports.remove = function (req, res, next) {
	const id = req.params.id;
	DataModel.findByIdAndRemove(id, function (err, data) {
		res.json(data);
	})
}
//分页
exports.list = function (req, res, next) {
	var page = (req.body.page) ? req.body.page : 1;
	var limit = (req.body.limit) ? req.body.limit : 10;
	//定义查询条件
	var queryCondition = {};
	if (req.body.name && req.body.name.trim().length > 0) {
		name = req.body.name;
		queryCondition = {
			'name': new RegExp(name, 'i')
		}
	}
	DataModel.paginate(queryCondition, { sort: { _id: -1 }, page: parseInt(page), limit: parseInt(limit) },
		function (err, result) {
			result.rows = result.docs;
			delete result.docs;
			res.json(result)
		});
}
//多个删除
exports.deletes = function (req, res, next) {
	const ids = req.body.ids;
	if (ids.length > 0) {
		DataModel.remove({ _id: { $in: ids.split(',') } })
			.then(data => {
				res.json({ "msg": "deletes success", "status": 200 });
			})
	} else {
		res.json({ "msg": "deletes fail", "status": 404 });
	}
}